<script setup>
import { ref, watch, computed } from 'vue'

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    required: true,
  },
  // 列配置
  columns: {
    type: Array,
    required: true,
  },
  // 分页配置
  pagination: {
    type: Object,
    default: () => ({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
  },
  height: {
    type: [String, Number],
    default: '100%'
  },
  rowKey: {
    type: String,
    default: 'id'
  },
  showSelection: {
    type: Boolean,
    default: true
  },
  // 添加禁用选择的行的条件函数
  selectionDisabled: {
    type: Function,
    default: () => false
  }
})

const emit = defineEmits(['action', 'selection-change', 'update:pagination'])

// 在组件内维护选中状态
const multipleSelection = ref([])

// 处理分页变化
const handlePageChange = (page) => {
  emit('update:pagination', { ...props.pagination, currentPage: page })
}

const handleSizeChange = (size) => {
  emit('update:pagination', { ...props.pagination, pageSize: size, currentPage: 1 })
}

// 处理操作按钮点击
const handleAction = (action, row) => {
  emit('action', { action, row })
}

// 简化选择处理逻辑
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
  emit('selection-change', selection)
}

// 提供获取已选择行的方法和设置选中状态方法
const getSelectedRows = () => multipleSelection.value
const setSelection = (rows) => {
  // 清空当前选择
  tableRef.value?.clearSelection()
  
  // 设置新的选择
  if (rows && rows.length) {
    // 延迟执行以确保表格已经渲染
    setTimeout(() => {
      rows.forEach(row => {
        const found = props.data.find(item => item[props.rowKey] === row[props.rowKey])
        if (found && !props.selectionDisabled(found)) {
          tableRef.value?.toggleRowSelection(found, true)
        }
      })
    }, 100)
  }
}

// 控制选择框是否禁用
const selectionDisabledClass = (row) => {
  return props.selectionDisabled(row) ? 'selection-disabled' : ''
}

// 行选择前的处理
const handleSelectionChange2 = (row, selected) => {
  // 如果行被禁用选择且尝试选中它，则阻止选择
  if (props.selectionDisabled(row) && selected) {
    // 在下一个事件循环取消选择
    setTimeout(() => {
      tableRef.value?.toggleRowSelection(row, false)
    }, 0)
    return false
  }
  return true
}

// 合并导出方法
defineExpose({
  getSelectedRows,
  setSelection
})

// 计算序号
const getIndex = (index) => {
  return (props.pagination.currentPage - 1) * props.pagination.pageSize + index + 1
}

const tableRef = ref(null)  // 添加表格引用

// 确认展示的列
const visibleColumns = computed(() => {
  return props.columns
})

</script>

<template>
  <div class="data-table-container">
    <el-table
      ref="tableRef"
      :data="data"
      :height="height"
      border
      stripe
      :row-key="rowKey"
      @selection-change="handleSelectionChange"
      :class="{ 'has-selection-disabled': true }"
      :header-cell-style="{
        background: 'var(--el-bg-color-overlay)',
        color: 'var(--el-text-color-primary)',
        borderColor: 'var(--el-border-color)'
      }"
      :cell-style="{
        borderColor: 'var(--el-border-color)'
      }"
      :row-class-name="selectionDisabledClass"
      @select="handleSelectionChange2"
    >
      <!-- 选择列 -->
      <el-table-column
        v-if="showSelection"
        type="selection"
        width="55"
        align="center"
        fixed="left"
        :selectable="(row) => !selectionDisabled(row)"
      />
      
      <!-- 动态列 -->
      <template v-for="(column, index) in visibleColumns" :key="index">
        <!-- 使用插槽的列 -->
        <el-table-column
          v-if="column.slot"
          :label="column.label"
          :width="column.width"
          :align="column.align || 'left'"
          :fixed="column.fixed"
        >
          <template #default="scope">
            <slot :name="column.slot" :row="scope.row" :$index="scope.$index">
              <!-- 默认操作按钮 -->
              <el-button-group v-if="column.slot === 'actions'">
                <el-button link type="primary" @click="handleAction('edit', scope.row)">
                  编辑
                </el-button>
                <el-button link type="danger" @click="handleAction('delete', scope.row)">
                  删除
                </el-button>
              </el-button-group>
            </slot>
          </template>
        </el-table-column>
        
        <!-- 普通列 -->
        <el-table-column
          v-else
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :align="column.align || 'left'"
          :sortable="column.sortable"
          :fixed="column.fixed"
        >
          <template v-if="column.formatter" #default="scope">
            {{ column.formatter(scope.row, column, scope.$index) }}
          </template>
        </el-table-column>
      </template>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-if="pagination && pagination.total > 0"
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.data-table-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 200px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color);
  --el-table-header-bg-color: var(--el-bg-color-overlay);
  background-color: var(--el-bg-color);
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td.el-table__cell) {
  background-color: var(--el-fill-color-lighter);
}

:deep(.el-table .el-table__body tr.el-table__row td.el-table__cell) {
  background-color: var(--el-bg-color);
}

:deep(.el-table .el-table__empty-block) {
  background-color: var(--el-bg-color);
}

:deep(.el-table__cell) {
  color: var(--el-text-color-primary);
}

:deep(.el-pagination) {
  --el-pagination-button-bg-color: var(--el-bg-color);
  --el-pagination-button-color: var(--el-text-color-primary);
  --el-pagination-hover-color: var(--el-color-primary);
}

:deep(.el-pagination .el-select .el-input .el-input__wrapper) {
  background-color: var(--el-bg-color);
}

/* 禁用选择的行样式 */
:deep(.selection-disabled .el-checkbox__input.is-disabled) {
  cursor: not-allowed;
}

:deep(.selection-disabled .el-checkbox__input.is-disabled .el-checkbox__inner) {
  background-color: var(--el-fill-color-lighter);
  border-color: var(--el-border-color-lighter);
}

:deep(.selection-disabled) {
  opacity: 0.7;
}
</style>
